import { defineStore } from 'pinia'
import { api } from '@/utils/request'

const API_BASE = '/api/auth'

async function parseError(res: Response) {
  try {
    const data = await res.json()
    return data?.error || res.statusText || '요청 실패'
  } catch {
    try {
      const text = await res.text()
      return text || res.statusText || '요청 실패'
    } catch {
      return res.statusText || '요청 실패'
    }
  }
}

export const useAuthStore = defineStore('KoreanFakeClientAuth', {
  state: () => ({
    user: null as null | {
      id: string | number
      loginId?: string
      email?: string
      name?: string | null
      nickname?: string | null
      phone?: string | null
      gender?: string | null
      birthdate?: string | null
      avatarUrl?: string | null
      memberLevel?: string
      role?: string
      status?: string
    },
    loading: false,
    error: '' as string,
  }),
  persist: {
    key: 'client_auth',
    storage: localStorage,
    pick: ['user']
  },
  actions: {
    async fetchMe() {
      this.loading = true
      this.error = ''
      try {
        const res = await api.get(`${API_BASE}/me`)
        if (!res.ok) {
          // 401 错误是正常的未登录状态，不需要设置错误信息
          if (res.status === 401) {
            this.user = null
            return
          }
          throw new Error(await parseError(res))
        }
        this.user = await res.json()
      } catch (e: any) {
        this.user = null
        // 只有非 401 错误才设置错误信息
        if (e?.message && !e.message.includes('401') && !e.message.includes('未登录')) {
          this.error = e?.message || '사용자 정보 가져오기 실패'
        }
      } finally {
        this.loading = false
      }
    },
    async login(payload: { identifier: string; password: string; rememberMe: boolean }) {
      this.loading = true
      this.error = ''
      try {
        const res = await api.post(`${API_BASE}/login`, payload)
        if (!res.ok) throw new Error(await parseError(res))
        const u = await res.json()

        // 先设置基本用户信息
        this.user = { id: u.id, loginId: u.login_id, email: u.email }

        // 登录成功后获取完整用户信息
        await this.fetchMe()

        // 确认用户信息已正确设置
        if (!this.user || !this.user.id) {
          throw new Error('로그인 성공했지만 사용자 정보 가져오기 실패')
        }

        return true
      } catch (e: any) {
        this.error = e?.message || '로그인 실패'
        return false
      } finally {
        this.loading = false
      }
    },
    async register(payload: {
      login_id: string
      email: string
      password: string
      name?: string
      nickname?: string
      phone?: string
      gender?: string
      birthdate?: string
      partner_code: string
    }) {
      this.loading = true
      this.error = ''
      try {
        const normalized = { ...payload }
        if (normalized.birthdate) {
          normalized.birthdate = normalized.birthdate.split('/').join('-')
        }
        const res = await api.post(`${API_BASE}/register`, normalized)
        if (!res.ok) throw new Error(await parseError(res))
        const u = await res.json()

        // 先设置基本用户信息
        this.user = { id: u.id, loginId: u.login_id, email: u.email }

        // 注册成功后获取完整用户信息，确保状态同步
        await this.fetchMe()

        // 再次确认用户信息已正确设置
        if (!this.user || !this.user.id) {
          throw new Error('가입 성공했지만 사용자 정보 가져오기 실패, 다시 로그인해주세요')
        }

        return true
      } catch (e: any) {
        this.error = e?.message || '가입 실패'
        return false
      } finally {
        this.loading = false
      }
    },
    async logout() {
      this.loading = true
      try {
        await api.post(`${API_BASE}/logout`)
      } finally {
        this.user = null
        this.loading = false
      }
    },

    // 强制刷新用户信息（清除缓存）
    async refreshUserInfo() {
      await this.fetchMe()
    },

    // 检查用户是否真正已登录（包含完整信息）
    isUserFullyLoaded() {
      return !!(this.user && this.user.id && (this.user.loginId || this.user.email))
    },

    // 确保用户状态完整性
    async ensureUserState() {
      if (!this.isUserFullyLoaded()) {
        await this.fetchMe()
      }
      return this.isUserFullyLoaded()
    },
  },
})

